
package com.scalar.chiptrack.alarms.jobs;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.dao.AlarmDAO;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;


public class TimedOutAlarmsMonitorJob extends JobHandler {


    public TimedOutAlarmsMonitorJob() {
    }
    
    public void execute() throws Exception {
        
        System.out.print ("TimedOutAlarmsMonitorJob: scanning thru through all open alarms for expired alarms...");

        ArrayList openAlarmList = null;
        try {
            openAlarmList = AlarmDAO.loadOpenAlarms();

            Alarm alarm = null;
            long now = System.currentTimeMillis();
            long expiresOn = -1;

            if (openAlarmList == null) {
                System.out.println ("No open Alarms found");
                return;
            }


            HashMap originatorAlarmMap = new HashMap();
            ArrayList alarmList = null;
            String originator = null;
            
            int listSize = openAlarmList.size();
            for (int i=0; i<listSize; i++) {

                alarm = (Alarm) openAlarmList.get(i);
                expiresOn = alarm.getExpiresOn();

                if (expiresOn <= now) {   // expired
                    
                    originator = alarm.getOriginator().getName();
                    alarmList = (ArrayList) originatorAlarmMap.get (originator);
                    
                    if (alarmList == null) {
                        alarmList = new ArrayList();
                        originatorAlarmMap.put (originator, alarmList);
                    }
                    
                    alarmList.add (alarm);
                }
            }
            
            sendAlert (originatorAlarmMap);
        }
        catch (Exception e) {
            System.err.println ("Exception while running TimedOutAlarmsMonitorJob: " + e);
            e.printStackTrace();
            throw e;
        } 
    }
    
    
    private void sendAlert (HashMap originatorAlarmMap) throws Exception {
        
        Iterator originatorIterator = originatorAlarmMap.keySet().iterator();
        String originator = null;
        Iterator alarmIterator = null;
        Alarm alarm = null;

        String subject = "ChipTrac: Notifications Timed out";
        String from = ConfigManager.getSysAdminEmail();
        String to = null;
        StringBuffer message = new StringBuffer();
        
        String hostName = ConfigManager.getChipTracHost();
        String context = ConfigManager.getChipTracContext();
        String[] bgColor = {"#DEE1E2", "#FFFFFF"};
        
        int i=0;
        while (originatorIterator.hasNext()) {
            originator = (String) originatorIterator.next();
            alarmIterator = ((ArrayList) originatorAlarmMap.get (originator)).iterator();
            
            message.append ("<html><head><link href='http://").append (hostName).append ("/").append (context).append ("/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet><BR>\n");
            message.append ("</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'><BR>\n");
            message.append ("<IMG src='http://").append (hostName).append ("/").append (context).append ("/jsp/includes/images/scalar_logo.jpg' width=90 height=36 border=0>\n");
            message.append ("<center><h3>Timed out Notifications</h3></center><p>Hi, The notifications listed below are timed out before anybody has responded to it. Please click on the links below to view the notification information in detail:<p>\n");
            message.append ("<table border='0' align='center' width='70%'>\n\t<tr bgcolor='#993333'><td><font color='#FFFFFF'>Alarm ID</font></td><td><font color='#FFFFFF'>Alarm Name</font></td><td><font color='#FFFFFF'>Alarm Type</font></td><td><font color='#FFFFFF'>Created On</font></td></tr>\n");

            i = 0;
            while (alarmIterator.hasNext()) {

                alarm = (Alarm) alarmIterator.next();    

                message.append ("<tr bgcolor='" + bgColor[(i++)%2] + "'><td><a href='http://").append (hostName).append ("/").append (context);
                message.append ("/alarmsWarnings.do?action=show&alarmId=").append (alarm.getId()).append ("&alarmType=").append (alarm.getType()).append ("' title='Click here to view details'>");                
                message.append (alarm.getId()).append ("</a></td><td>").append (alarm.getName()).append ("</td><td>");
                message.append (alarm.getType()).append ("</td><td>").append (StringUtils.formatDateToString (new Date (alarm.getCreatedOn()))).append ("</td></tr>\n");
            }
            
            message.append ("</table></body></html>\n");

            to = alarm.getOriginator().getEmail();

            Mailer.send (from, to, subject, message.toString(), Mailer.CONTENT_TYPE_HTML);
            System.out.println ("NotificationReminder: Sent timed out notification information to " + originator + " (" + to + ")");
        }
        
    }

    
    public static void main (String[] args) throws Exception {
        new TimedOutAlarmsMonitorJob().execute();
    }
}